package com.eshipenet.shipnet.shiprpc.grpc;

import com.eshipenet.shipnet.ship.FindAllResult;
import com.eshipenet.shipnet.ship.grpc.*;
import com.eshipenet.shipnet.shiprpc.service.ShipGovernorLinkService;
import com.eshipenet.shipnet.shiprpc.service.ShipGovernorService;
import com.eshipenet.shipnet.shiprpc.service.ShipService;
import com.eshipenet.shipnet.shiprpc.util.GetJObjectUtil;
import com.eshipenet.shipnet.shiprpc.util.TimestampToDate;
import com.google.protobuf.Struct;
import io.grpc.stub.StreamObserver;
import org.json4s.JsonAST;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Option;
import scala.collection.immutable.List;
import squirrel.JSONQuery;

import java.util.ArrayList;

public class ShipGovernorLinkRepoGrpcImpl extends ShipGovernorLinkRepoGrpc.ShipGovernorLinkRepoImplBase {
    private Logger logger = LoggerFactory.getLogger("ShipGovernorLinkRepoGrpcImpl");
    private ShipGovernorLinkService service;
    private ShipGovernorService shipGovernorService;
    private ShipService shipService;

    public ShipGovernorLinkRepoGrpcImpl(ShipGovernorLinkService service, ShipGovernorService shipGovernorService, ShipService shipService) {
        this.service = service;
        this.shipGovernorService = shipGovernorService;
        this.shipService = shipService;
    }



    /**
     * 查询列表
     *
     * @param req
     * @param responseObserver
     */
    public void findAll(ShipGovernorLinkFindAllRequest req, StreamObserver<ShipGovernorLinkFindAllReply> responseObserver) {

        try {
            logger.info("ShipGovernorLinkRepoGrpcImpl.findAll.Filter    {}", req.getFilter());
            ShipGovernorLinkFindAllReply reply = findAllInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }


    /**
     * 创建
     *
     * @param req
     * @param responseObserver
     */
    public void createOne(ShipGovernorLinkCreateOneRequest req, StreamObserver<ShipGovernorLinkCreateOneReply> responseObserver) {
        try {
            logger.info("ShipGovernorLinkRepoGrpcImpl.createOne.data   {}", req.getData());
            ShipGovernorLinkCreateOneReply reply = createOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }

    /**
     * 修改
     *
     * @param req
     * @param responseObserver
     */
    public void updateOne(ShipGovernorLinkUpdateOneRequest req, StreamObserver<ShipGovernorLinkUpdateOneReply> responseObserver) {
        try {
            logger.info("ShipGovernorLinkRepoGrpcImpl.updateOne.data   {}", req.getData());
            ShipGovernorLinkUpdateOneReply reply = updateOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }


    /**
     * 删除
     *
     * @param req
     * @param responseObserver
     */
    public void deleteOne(ShipGovernorLinkDeleteOneRequest req, StreamObserver<ShipGovernorLinkDeleteOneReply> responseObserver) {
        try {
            logger.info("ShipGovernorLinkRepoGrpcImpl.deleteOne.ShipId  {}  . ShipGovernorId  {} ", req.getShipId(), req.getShipGovernorId());
            ShipGovernorLinkDeleteOneReply reply = deleteOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }

    public ShipGovernorLinkFindAllReply findAllInner(ShipGovernorLinkFindAllRequest req) {

        int limit = req.getFilter().getLimit();
        int offset = req.getFilter().getOffset();

        if (limit == 0) {
            limit = 500;

        }
        if (offset == 0) {
            offset = 1;

        }

        //查询条件
        Struct wheres = req.getFilter().getWhere();

        JsonAST.JObject jObject = GetJObjectUtil.getWhere(wheres);

        //联合查询
        java.util.List<ShipGovernorLinkFindAllFilterInclude> in_list = req.getFilter().getIncludeList();

        ArrayList<JsonAST.JValue> arrayList = new ArrayList<>();

        for (ShipGovernorLinkFindAllFilterInclude include : in_list) {

            JsonAST.JValue jValue = new JsonAST.JString(include.getName());

            arrayList.add(jValue);

        }
        List<JsonAST.JValue> includes_list = scala.collection.JavaConverters.asScalaIterator(arrayList.iterator()).toList();

        JsonAST.JArray jArray = new JsonAST.JArray(includes_list);

        //生成查询列表的sql
        JSONQuery jsonQuery = JSONQuery.apply(new JsonAST.JString("ShipGovernorLink"),
                Option.apply(jObject),
                Option.apply(new JsonAST.JString("*")),
                Option.apply(jArray),
                Option.apply(null),
                Option.apply(null));

        FindAllResult result = service.findAll(jsonQuery, limit, offset);
        //数据总数
        int totalCount = result.getTotalCount();
        //列表数据
        java.util.List list = new ArrayList<>();
        //判断是否有数据，无数据时直接返回
        if (totalCount < 1) {
            //设置分页信息
            PageInfo pageInfo = PageInfo.newBuilder()
                    .setHasNextPage(result.isHasNextPage())
                    .setHasPreviousPage(result.isHasPreviousPage())
                    .build();

            return ShipGovernorLinkFindAllReply.newBuilder()
                    .setReq(req)
                    .addAllEdges(list)
                    .setPageInfo(pageInfo)
                    .setTotalCount(0).build();
        }

        list = result.getList();

        //设置分页信息
        PageInfo pageInfo = PageInfo.newBuilder()
                .setHasNextPage(result.isHasNextPage())
                .setHasPreviousPage(result.isHasPreviousPage())
                .setStartCursor(result.getStartCursor())
                .setEndCursor(result.getEndCursor()).build();


        return ShipGovernorLinkFindAllReply.newBuilder()
                .setReq(req)
                .addAllEdges(list)
                .setPageInfo(pageInfo)
                .setTotalCount(totalCount).build();
    }


    public ShipGovernorLinkCreateOneReply createOneInner(ShipGovernorLinkCreateOneRequest req) {

        //获取当前时间
        java.sql.Timestamp createdAt = new java.sql.Timestamp(System.currentTimeMillis());

        String shipId = req.getData().getShipId();
        String shipGovernorId = req.getData().getShipGovernorId();
        if (!shipId.isEmpty()) {
            int count = shipService.getShipCountById(shipId);
            if (count < 1) {
                try {
                    throw new Exception("invalid shipId!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (!shipGovernorId.isEmpty()) {
            int count = shipGovernorService.getShipGovernorCountById(shipGovernorId);
            if (count < 1) {
                try {
                    throw new Exception("invalid shipGovernorId!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        com.eshipenet.shipnet.ship.ShipGovernorLink shipGovernorLink = new com.eshipenet.shipnet.ship.ShipGovernorLink(
                createdAt,
                createdAt,
                req.getData().getShipId(),
                req.getData().getShipGovernorId());

        shipGovernorLink = service.createOne(shipGovernorLink);

        ShipGovernorLink ShipGovernorLinkBuilder = ShipGovernorLink.newBuilder()
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipGovernorLink.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipGovernorLink.getCreatedAt()))
                .setShipId(shipGovernorLink.getShipId())
                .setShipGovernorId(shipGovernorLink.getShipGovernorId())
                .build();

        return ShipGovernorLinkCreateOneReply.newBuilder().setData(ShipGovernorLinkBuilder).setReq(req).build();


    }


    public ShipGovernorLinkUpdateOneReply updateOneInner(ShipGovernorLinkUpdateOneRequest req) {
        //获取当前时间
        java.sql.Timestamp updatedAt = new java.sql.Timestamp(System.currentTimeMillis());
        com.eshipenet.shipnet.ship.ShipGovernorLink shipGovernorLink = new com.eshipenet.shipnet.ship.ShipGovernorLink(
                null,
                updatedAt,
                req.getData().getShipId(),
                req.getData().getShipGovernorId()
        );

        shipGovernorLink = service.updateOne(shipGovernorLink);

        ShipGovernorLink ShipGovernorLinkBuilder = ShipGovernorLink.newBuilder()
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipGovernorLink.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipGovernorLink.getCreatedAt()))
                .setShipId(shipGovernorLink.getShipId())
                .setShipGovernorId(shipGovernorLink.getShipGovernorId())
                .build();


        return ShipGovernorLinkUpdateOneReply.newBuilder().setData(ShipGovernorLinkBuilder).setReq(req).build();


    }


    public ShipGovernorLinkDeleteOneReply deleteOneInner(ShipGovernorLinkDeleteOneRequest req) {

        String shipId = req.getShipId();
        String shipGovernorId = req.getShipGovernorId();
        com.eshipenet.shipnet.ship.ShipGovernorLink shipGovernorLink = service.deleteOne(shipId, shipGovernorId);

        ShipGovernorLink ShipGovernorLinkBuilder = ShipGovernorLink.newBuilder()
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipGovernorLink.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipGovernorLink.getCreatedAt()))
                .setShipId(shipGovernorLink.getShipId())
                .setShipGovernorId(shipGovernorLink.getShipGovernorId())
                .build();

        return ShipGovernorLinkDeleteOneReply.newBuilder().setData(ShipGovernorLinkBuilder).setReq(req).build();

    }

}

